package main

import (
	"fmt"
	"io"
	"net"
	"strings"
	"sync"
	"time"
)

type Server struct {
	Ip   string
	Port int
	// 在线用户列表
	mapLock   sync.RWMutex
	OnlineMap map[string]*User
	// 消息广播channel
	Message chan string
}

func NewServer(ip string, port int) *Server {
	server := &Server{
		Ip:        ip,
		Port:      port,
		OnlineMap: make(map[string]*User),
		Message:   make(chan string),
	}
	return server
}

func (receiver *Server) Handler(conn net.Conn) {
	//fmt.Println("connect success")
	user := NewUser(conn)
	receiver.mapLock.RLock()
	receiver.OnlineMap[user.Name] = user
	receiver.mapLock.RUnlock()

	//广播用户上线信息
	receiver.BroadCast(user, "online!")

	isLive := make(chan bool)

	//接收客户端发送的消息
	go func() {
		buf := make([]byte, 1024)
		for {
			n, err := conn.Read(buf)
			if n == 0 {
				receiver.BroadCast(user, "offline!")
				receiver.mapLock.Lock()
				delete(receiver.OnlineMap, user.Name)
				receiver.mapLock.Unlock()
				return
			}
			if err != nil && err != io.EOF {
				fmt.Println("Conn Read error: ", err)
				return
			}
			msg := string(buf[:n-1])
			//查询在线用户
			if msg == "who" {
				receiver.mapLock.Lock()
				for name, _ := range receiver.OnlineMap {
					if name == user.Name {
						continue
					}
					user.SendMsg(name + " online\n")
				}
				receiver.mapLock.Unlock()
			} else if len(msg) > 2 && msg[:2] == "to" {
				remoteName := strings.Split(msg, "|")[1]
				sendmsg := strings.Split(msg, "|")[2]
				receiver.OnlineMap[remoteName].SendMsg(sendmsg)
			} else if len(msg) > 6 && msg[:6] == "rename" {
				oldName := user.Name
				user.Name = strings.Split(msg, "|")[1]
				delete(receiver.OnlineMap, oldName)
				receiver.OnlineMap[user.Name] = user
			} else {
				receiver.BroadCast(user, msg)
			}
			isLive <- true
		}
	}()

	for {
		select {
		case <-isLive:
		case <-time.After(100 * time.Second):
			user.SendMsg("You are Out!")
			close(user.C)
			conn.Close()
			return
		}
	}
}

func (receiver *Server) ListenMessage() {
	for {
		msg := <-receiver.Message
		receiver.mapLock.Lock()
		for _, cli := range receiver.OnlineMap {
			cli.C <- msg
		}
		receiver.mapLock.Unlock()
	}
}

func (receiver *Server) BroadCast(user *User, msg string) {
	sendMsg := "[" + user.Addr + "]" + user.Name + ": " + msg
	receiver.Message <- sendMsg
}

// 启动服务器
func (receiver *Server) Start() {
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", receiver.Ip, receiver.Port))
	if err != nil {
		fmt.Println("listen error")
		return
	}
	defer listener.Close()

	go receiver.ListenMessage()

	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("accept error: ", err)
			continue
		}

		go receiver.Handler(conn)
	}
}
